home *** CD-ROM | disk | FTP | other *** search
/ Programming an RTS Game with Direct3D / Programming an RTS Game with Direct3D.iso / Examples / Chapter 9 / Example 9.1 / terrain.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2006-07-14  |  25.5 KB  |  936 lines

  1. #include "terrain.h"
  2. #include "camera.h"
  3.  
  4. const DWORD TERRAINVertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX2;
  5.  
  6. //////////////////////////////////////////////////////////////////////////////////////////
  7. //                                    PATCH                                                //
  8. //////////////////////////////////////////////////////////////////////////////////////////
  9.  
  10. PATCH::PATCH()
  11. {
  12.     m_pDevice = NULL;
  13.     m_pMesh = NULL;
  14. }
  15. PATCH::~PATCH()
  16. {
  17.     Release();
  18. }
  19.  
  20. void PATCH::Release()
  21. {
  22.     if(m_pMesh != NULL)
  23.         m_pMesh->Release();
  24.     m_pMesh = NULL;
  25. }
  26.  
  27. HRESULT PATCH::CreateMesh(TERRAIN &ter, RECT source, IDirect3DDevice9* Dev)
  28. {
  29.     if(m_pMesh != NULL)
  30.     {
  31.         m_pMesh->Release();
  32.         m_pMesh = NULL;
  33.     }
  34.  
  35.     try
  36.     {
  37.         m_pDevice = Dev;
  38.         m_mapRect = source;
  39.  
  40.         int width = source.right - source.left;
  41.         int height = source.bottom - source.top;
  42.         int nrVert = (width + 1) * (height + 1);
  43.         int nrTri = width * height * 2;
  44.  
  45.         if(FAILED(D3DXCreateMeshFVF(nrTri, nrVert, D3DXMESH_MANAGED, TERRAINVertex::FVF, m_pDevice, &m_pMesh)))
  46.         {
  47.             debug.Print("Couldn't create mesh for PATCH");
  48.             return E_FAIL;
  49.         }
  50.  
  51.         m_BBox.max = D3DXVECTOR3(-10000.0f, -10000.0f, -10000.0f);
  52.         m_BBox.min = D3DXVECTOR3(10000.0f, 10000.0f, 10000.0f);
  53.  
  54.         //Create vertices
  55.         TERRAINVertex* ver = 0;
  56.         m_pMesh->LockVertexBuffer(0,(void**)&ver);
  57.         for(int z=source.top, z0 = 0;z<=source.bottom;z++, z0++)
  58.             for(int x=source.left, x0 = 0;x<=source.right;x++, x0++)
  59.             {
  60.                 MAPTILE *tile = ter.GetTile(x, z);
  61.  
  62.                 D3DXVECTOR3 pos = D3DXVECTOR3(x, tile->m_height, -z);
  63.                 D3DXVECTOR2 alphaUV = D3DXVECTOR2(x / (float)ter.m_size.x, z / (float)ter.m_size.y);        //Alpha UV
  64.                 D3DXVECTOR2 colorUV = alphaUV * 8.0f;                                                    //Color UV
  65.  
  66.                 ver[z0 * (width + 1) + x0] = TERRAINVertex(pos, ter.GetNormal(x, z), alphaUV, colorUV);
  67.  
  68.                 //Calculate bounding box bounds...
  69.                 if(pos.x < m_BBox.min.x)m_BBox.min.x = pos.x;
  70.                 if(pos.x > m_BBox.max.x)m_BBox.max.x = pos.x;
  71.                 if(pos.y < m_BBox.min.y)m_BBox.min.y = pos.y;
  72.                 if(pos.y > m_BBox.max.y)m_BBox.max.y = pos.y;
  73.                 if(pos.z < m_BBox.min.z)m_BBox.min.z = pos.z;
  74.                 if(pos.z > m_BBox.max.z)m_BBox.max.z = pos.z;
  75.             }
  76.         m_pMesh->UnlockVertexBuffer();
  77.  
  78.         //Calculate Indices
  79.         WORD* ind = 0;
  80.         m_pMesh->LockIndexBuffer(0,(void**)&ind);    
  81.         int index = 0;
  82.  
  83.         for(int z=source.top, z0 = 0;z<source.bottom;z++, z0++)
  84.             for(int x=source.left, x0 = 0;x<source.right;x++, x0++)
  85.             {
  86.                 //Triangle 1
  87.                 ind[index++] =   z0   * (width + 1) + x0;
  88.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  89.                 ind[index++] = (z0+1) * (width + 1) + x0;        
  90.  
  91.                 //Triangle 2
  92.                 ind[index++] = (z0+1) * (width + 1) + x0;
  93.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  94.                 ind[index++] = (z0+1) * (width + 1) + x0 + 1;
  95.             }
  96.  
  97.         m_pMesh->UnlockIndexBuffer();
  98.  
  99.         //Set Attributes
  100.         DWORD *att = 0, a = 0;
  101.         m_pMesh->LockAttributeBuffer(0,&att);
  102.         memset(att, 0, sizeof(DWORD)*nrTri);
  103.         m_pMesh->UnlockAttributeBuffer();
  104.     }
  105.     catch(...)
  106.     {
  107.         debug.Print("Error in PATCH::CreateMesh()");
  108.         return E_FAIL;
  109.     }
  110.  
  111.     return S_OK;
  112. }
  113.  
  114. void PATCH::Render()
  115. {
  116.     //Draw mesh
  117.     if(m_pMesh != NULL)
  118.         m_pMesh->DrawSubset(0);
  119. }
  120.  
  121. //////////////////////////////////////////////////////////////////////////////////////////
  122. //                                    TERRAIN                                                //
  123. //////////////////////////////////////////////////////////////////////////////////////////
  124.  
  125. TERRAIN::TERRAIN()
  126. {
  127.     m_pDevice = NULL;
  128.     m_pMapTiles = NULL;
  129. }
  130.  
  131. void TERRAIN::Init(IDirect3DDevice9* Dev, INTPOINT _size)
  132. {
  133.     m_pDevice = Dev;
  134.     m_size = _size;
  135.     m_pHeightMap = NULL;
  136.  
  137.     if(m_pMapTiles != NULL)    //Clear old maptiles
  138.         delete [] m_pMapTiles;
  139.  
  140.     //Create maptiles
  141.     m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  142.     memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  143.  
  144.     //Clear old textures
  145.     for(int i=0;i<m_diffuseMaps.size();i++)
  146.         m_diffuseMaps[i]->Release();
  147.     m_diffuseMaps.clear();
  148.  
  149.     //Load textures
  150.     IDirect3DTexture9* grass = NULL, *mount = NULL, *snow = NULL;
  151.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/grass.jpg", &grass)))debug.Print("Could not load grass.jpg");
  152.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/mountain.jpg", &mount)))debug.Print("Could not load mountain.jpg");
  153.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/snow.jpg", &snow)))debug.Print("Could not load snow.jpg");
  154.     m_diffuseMaps.push_back(grass);
  155.     m_diffuseMaps.push_back(mount);
  156.     m_diffuseMaps.push_back(snow);
  157.     m_pAlphaMap = NULL;
  158.     m_pLightMap = NULL;
  159.  
  160.     // Init font
  161.     D3DXCreateFont(m_pDevice, 40, 0, 0, 1, false,  
  162.                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
  163.                    DEFAULT_PITCH | FF_DONTCARE, "Arial Black", &m_pProgressFont);
  164.  
  165.     //Load pixel & vertex shaders
  166.     m_dirToSun = D3DXVECTOR3(1.0f, 0.6f, 0.5f);
  167.     D3DXVec3Normalize(&m_dirToSun, &m_dirToSun);
  168.  
  169.     m_terrainPS.Init(Dev, "shaders/terrain.ps", PIXEL_SHADER);
  170.     m_terrainVS.Init(Dev, "shaders/terrain.vs", VERTEX_SHADER);
  171.     m_vsMatW = m_terrainVS.GetConstant("matW");
  172.     m_vsMatVP = m_terrainVS.GetConstant("matVP");
  173.     m_vsDirToSun = m_terrainVS.GetConstant("DirToSun");
  174.  
  175.     m_objectPS.Init(Dev, "shaders/objects.ps", PIXEL_SHADER);
  176.     m_objectVS.Init(Dev, "shaders/objects.vs", VERTEX_SHADER);
  177.     m_objMatW = m_objectVS.GetConstant("matW");
  178.     m_objMatVP = m_objectVS.GetConstant("matVP");
  179.     m_objDirToSun = m_objectVS.GetConstant("DirToSun");
  180.     m_objMapSize = m_objectVS.GetConstant("mapSize");
  181.  
  182.     //Create white material    
  183.     m_mtrl.Ambient = m_mtrl.Specular = m_mtrl.Diffuse  = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
  184.     m_mtrl.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
  185.  
  186.     GenerateRandomTerrain(9);
  187. }
  188.  
  189. void TERRAIN::Release()
  190. {
  191.     for(int i=0;i<m_patches.size();i++)
  192.         if(m_patches[i] != NULL)
  193.             m_patches[i]->Release();
  194.  
  195.     m_patches.clear();
  196.  
  197.     if(m_pHeightMap != NULL)
  198.     {
  199.         m_pHeightMap->Release();
  200.         delete m_pHeightMap;
  201.         m_pHeightMap = NULL;
  202.     }
  203.  
  204.     m_objects.clear();
  205. }
  206.  
  207. void TERRAIN::GenerateRandomTerrain(int numPatches)
  208. {
  209.     try
  210.     {
  211.         Release();
  212.  
  213.         //Create two heightmaps and multiply them
  214.         m_pHeightMap = new HEIGHTMAP(m_size, 20.0f);
  215.         HEIGHTMAP hm2(m_size, 2.0f);
  216.  
  217.         m_pHeightMap->CreateRandomHeightMap(rand()%2000, 1.0f, 0.7f, 7);
  218.         hm2.CreateRandomHeightMap(rand()%2000, 2.5f, 0.8f, 3);
  219.  
  220.         hm2.Cap(hm2.m_maxHeight * 0.4f);
  221.  
  222.         *m_pHeightMap *= hm2;
  223.         hm2.Release();
  224.         
  225.         //Add objects
  226.         HEIGHTMAP hm3(m_size, 1.0f);
  227.         hm3.CreateRandomHeightMap(rand()%1000, 5.5f, 0.9f, 7);
  228.  
  229.         for(int y=0;y<m_size.y;y++)
  230.             for(int x=0;x<m_size.x;x++)
  231.             {
  232.                 if(m_pHeightMap->GetHeight(x, y) == 0.0f && hm3.GetHeight(x, y) > 0.7f && rand()%6 == 0)
  233.                     AddObject(0, INTPOINT(x, y));    //Tree
  234.                 else if(m_pHeightMap->GetHeight(x, y) >= 1.0f && hm3.GetHeight(x, y) > 0.9f && rand()%20 == 0)
  235.                     AddObject(1, INTPOINT(x, y));    //Stone
  236.             }
  237.  
  238.         hm3.Release();
  239.  
  240.         InitPathfinding();
  241.         CreatePatches(numPatches);
  242.         CalculateAlphaMaps();
  243.         CalculateLightMap(false);
  244.     }
  245.     catch(...)
  246.     {
  247.         debug.Print("Error in TERRAIN::GenerateRandomTerrain()");
  248.     }
  249. }
  250.  
  251. void TERRAIN::CreatePatches(int numPatches)
  252. {
  253.     try
  254.     {
  255.         //Clear any old patches
  256.         for(int i=0;i<m_patches.size();i++)
  257.             if(m_patches[i] != NULL)
  258.                 m_patches[i]->Release();
  259.         m_patches.clear();
  260.  
  261.         //Create new patches
  262.         for(int y=0;y<numPatches;y++)
  263.         {
  264.             Progress("Creating Terrain Mesh", y / (float)numPatches);
  265.  
  266.             for(int x=0;x<numPatches;x++)
  267.             {
  268.                 RECT r = {x * (m_size.x - 1) / (float)numPatches, 
  269.                           y * (m_size.y - 1) / (float)numPatches, 
  270.                         (x+1) * (m_size.x - 1) / (float)numPatches,
  271.                         (y+1) * (m_size.y - 1) / (float)numPatches};
  272.                         
  273.                 PATCH *p = new PATCH();
  274.                 p->CreateMesh(*this, r, m_pDevice);
  275.                 m_patches.push_back(p);
  276.             }
  277.         }
  278.     }
  279.     catch(...)
  280.     {
  281.         debug.Print("Error in TERRAIN::CreatePatches()");
  282.     }
  283. }
  284.  
  285. void TERRAIN::CalculateAlphaMaps()
  286. {
  287.     Progress("Creating Alpha Map", 0.0f);
  288.  
  289.     //Clear old alpha maps
  290.     if(m_pAlphaMap != NULL)
  291.         m_pAlphaMap->Release();
  292.  
  293.     //Create new alpha map
  294.     D3DXCreateTexture(m_pDevice, 128, 128, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pAlphaMap);
  295.  
  296.     //Lock the texture
  297.     D3DLOCKED_RECT sRect;
  298.     m_pAlphaMap->LockRect(0, &sRect, NULL, NULL);
  299.     BYTE *bytes = (BYTE*)sRect.pBits;
  300.     memset(bytes, 0, 128*sRect.Pitch);        //Clear texture to black
  301.  
  302.     for(int i=0;i<m_diffuseMaps.size();i++)
  303.         for(int y=0;y<sRect.Pitch / 4;y++)
  304.             for(int x=0;x<sRect.Pitch / 4;x++)
  305.             {
  306.                 int terrain_x = m_size.x * (x / (float)(sRect.Pitch / 4.0f));
  307.                 int terrain_y = m_size.y * (y / (float)(sRect.Pitch / 4.0f));
  308.                 MAPTILE *tile = GetTile(terrain_x, terrain_y);
  309.  
  310.                 if(tile != NULL && tile->m_type == i)
  311.                     bytes[y * sRect.Pitch + x * 4 + i] = 255;
  312.             }
  313.  
  314.     //Unlock the texture
  315.     m_pAlphaMap->UnlockRect(0);
  316.     
  317.     //D3DXSaveTextureToFile("alpha.bmp", D3DXIFF_BMP, m_pAlphaMap, NULL);
  318. }
  319.  
  320. void TERRAIN::CalculateLightMap(bool allWhite)
  321. {
  322.     try
  323.     {
  324.         //Clear old alpha maps
  325.         if(m_pLightMap != NULL)
  326.             m_pLightMap->Release();
  327.  
  328.         //Create new light map
  329.         D3DXCreateTexture(m_pDevice, 256, 256, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &m_pLightMap);
  330.  
  331.         //Lock the texture
  332.         D3DLOCKED_RECT sRect;
  333.         m_pLightMap->LockRect(0, &sRect, NULL, NULL);
  334.         BYTE *bytes = (BYTE*)sRect.pBits;
  335.         memset(bytes, 255, 256*sRect.Pitch);        //Clear texture to white
  336.  
  337.         if(allWhite)
  338.         {
  339.             m_pLightMap->UnlockRect(0);
  340.             return;
  341.         }
  342.  
  343.         for(int y=0;y<sRect.Pitch;y++)
  344.         {
  345.             Progress("Calculating Lightmap", y / (float)sRect.Pitch);
  346.  
  347.             for(int x=0;x<sRect.Pitch;x++)
  348.             {
  349.                 float terrain_x = (float)m_size.x * (x / (float)(sRect.Pitch));
  350.                 float terrain_z = (float)m_size.y * (y / (float)(sRect.Pitch));
  351.  
  352.                 //Find patch that the terrain_x, terrain_z is over
  353.                 bool done = false;
  354.                 for(int p=0;p<m_patches.size() && !done;p++)
  355.                 {
  356.                     RECT mr = m_patches[p]->m_mapRect;
  357.  
  358.                     //Focus within patch maprect or not?
  359.                     if(terrain_x >= mr.left && terrain_x < mr.right &&
  360.                          terrain_z >= mr.top && terrain_z < mr.bottom)
  361.                     {            
  362.                         // Collect only the closest intersection
  363.                         RAY rayTop(D3DXVECTOR3(terrain_x, 10000.0f, -terrain_z), D3DXVECTOR3(0.0f, -1.0f, 0.0f));
  364.                         float dist = rayTop.Intersect(m_patches[p]->m_pMesh);
  365.  
  366.                         if(dist >= 0.0f)
  367.                         {
  368.                             RAY ray(D3DXVECTOR3(terrain_x, 10000.0f - dist + 0.01f, -terrain_z), m_dirToSun);
  369.  
  370.                             for(int p2=0;p2<m_patches.size() && !done;p2++)
  371.                                 if(ray.Intersect(m_patches[p2]->m_BBox) >= 0)
  372.                                 {
  373.                                     if(ray.Intersect(m_patches[p2]->m_pMesh) >= 0)    //In shadow
  374.                                     {
  375.                                         done = true;
  376.                                         bytes[y * sRect.Pitch + x] = 128;
  377.                                     }
  378.                                 }
  379.  
  380.                             done = true;
  381.                         }
  382.                     }
  383.                 }                        
  384.             }
  385.         }
  386.  
  387.         //Smooth lightmap        
  388.         for(int i=0;i<3;i++)
  389.         {
  390.             Progress("Smoothing the Lightmap", i / 3.0f);
  391.  
  392.             BYTE* tmpBytes = new BYTE[sRect.Pitch * sRect.Pitch];
  393.             memcpy(tmpBytes, sRect.pBits, sRect.Pitch * sRect.Pitch);
  394.  
  395.             for(int y=1;y<sRect.Pitch-1;y++)
  396.                 for(int x=1;x<sRect.Pitch-1;x++)
  397.                 {
  398.                     long index = y*sRect.Pitch + x;
  399.                     BYTE b1 = bytes[index];
  400.                     BYTE b2 = bytes[index - 1];
  401.                     BYTE b3 = bytes[index - sRect.Pitch];
  402.                     BYTE b4 = bytes[index + 1];
  403.                     BYTE b5 = bytes[index + sRect.Pitch];
  404.                     
  405.                     tmpBytes[index] = (BYTE)((b1 + b2 + b3 + b4 + b5) / 5);
  406.                 }
  407.  
  408.             memcpy(sRect.pBits, tmpBytes, sRect.Pitch * sRect.Pitch);
  409.             delete [] tmpBytes;
  410.         }
  411.  
  412.         //Unlock the texture
  413.         m_pLightMap->UnlockRect(0);
  414.         
  415.         //D3DXSaveTextureToFile("light.bmp", D3DXIFF_BMP, m_pLightMap, NULL);
  416.     }
  417.     catch(...)
  418.     {
  419.         debug.Print("Error in TERRAIN::CalculateLightMap()");
  420.     }
  421. }
  422.  
  423. D3DXVECTOR3 TERRAIN::GetNormal(int x, int y)
  424. {
  425.     //Neighboring map nodes (D, B, C, F, H, G)
  426.     INTPOINT mp[] = {INTPOINT(x-1, y),   INTPOINT(x, y-1), 
  427.                      INTPOINT(x+1, y-1), INTPOINT(x+1, y),
  428.                        INTPOINT(x, y+1),   INTPOINT(x-1, y+1)};
  429.  
  430.     //if there's an invalid map node return (0, 1, 0)
  431.     if(!Within(mp[0]) || !Within(mp[1]) || !Within(mp[2]) || 
  432.        !Within(mp[3]) || !Within(mp[4]) || !Within(mp[5]))
  433.         return D3DXVECTOR3(0.0f, 1.0f, 0.0f);
  434.  
  435.     //Calculate the normals of the 6 neighboring planes
  436.     D3DXVECTOR3 normal = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
  437.  
  438.     for(int i=0;i<6;i++)
  439.     {
  440.         D3DXPLANE plane;
  441.         D3DXPlaneFromPoints(&plane, 
  442.                             &GetWorldPos(INTPOINT(x, y)),
  443.                             &GetWorldPos(mp[i]), 
  444.                             &GetWorldPos(mp[(i + 1) % 6]));
  445.  
  446.         normal +=  D3DXVECTOR3(plane.a, plane.b, plane.c);
  447.     }
  448.  
  449.     D3DXVec3Normalize(&normal, &normal);
  450.     return normal;
  451. }
  452.  
  453. void TERRAIN::AddObject(int type, INTPOINT mappos)
  454. {
  455.     D3DXVECTOR3 pos = D3DXVECTOR3(mappos.x, m_pHeightMap->GetHeight(mappos), -mappos.y);    
  456.     D3DXVECTOR3 rot = D3DXVECTOR3((rand()%1000 / 1000.0f) * 0.13f, (rand()%1000 / 1000.0f) * 3.0f, (rand()%1000 / 1000.0f) * 0.13);
  457.  
  458.     float sca_xz = (rand()%1000 / 1000.0f) * 0.5f + 0.5f;
  459.     float sca_y = (rand()%1000 / 1000.0f) * 1.0f + 0.5f;
  460.     D3DXVECTOR3 sca = D3DXVECTOR3(sca_xz, sca_y, sca_xz);
  461.  
  462.     m_objects.push_back(OBJECT(type, mappos, pos, rot, sca));
  463. }
  464.  
  465. void TERRAIN::Render(CAMERA &camera)
  466. {
  467.     //Set render states        
  468.     m_pDevice->SetRenderState(D3DRS_LIGHTING, false);
  469.     m_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, true);    
  470.     
  471.     m_pDevice->SetTexture(0, m_pAlphaMap);
  472.     m_pDevice->SetTexture(1, m_diffuseMaps[0]);        //Grass
  473.     m_pDevice->SetTexture(2, m_diffuseMaps[1]);        //Mountain
  474.     m_pDevice->SetTexture(3, m_diffuseMaps[2]);        //Snow
  475.     m_pDevice->SetTexture(4, m_pLightMap);            //Lightmap
  476.     m_pDevice->SetMaterial(&m_mtrl);
  477.  
  478.     D3DXMATRIX world, vp = camera.GetViewMatrix() * camera.GetProjectionMatrix();
  479.     D3DXMatrixIdentity(&world);
  480.     m_pDevice->SetTransform(D3DTS_WORLD, &world);
  481.     
  482.     //Set vertex shader variables
  483.     m_terrainVS.SetMatrix(m_vsMatW, world);
  484.     m_terrainVS.SetMatrix(m_vsMatVP, vp);
  485.     m_terrainVS.SetVector3(m_vsDirToSun, m_dirToSun);
  486.  
  487.     m_terrainVS.Begin();
  488.     m_terrainPS.Begin();
  489.         
  490.     for(int p=0;p<m_patches.size();p++)
  491.         if(!camera.Cull(m_patches[p]->m_BBox))
  492.             m_patches[p]->Render();
  493.  
  494.     m_terrainPS.End();
  495.     m_terrainVS.End();
  496.  
  497.     m_pDevice->SetTexture(1, NULL);
  498.     m_pDevice->SetTexture(2, NULL);
  499.     m_pDevice->SetTexture(3, NULL);
  500.     m_pDevice->SetTexture(4, NULL);
  501.  
  502.     //Render Objects
  503.     m_objectVS.SetMatrix(m_objMatW, world);
  504.     m_objectVS.SetMatrix(m_objMatVP, vp);
  505.     m_objectVS.SetVector3(m_objDirToSun, m_dirToSun);
  506.     m_objectVS.SetVector3(m_objMapSize, D3DXVECTOR3(m_size.x, m_size.y, 0.0f));
  507.  
  508.     m_pDevice->SetTexture(1, m_pLightMap);        //Lightmap
  509.     
  510.     m_objectVS.Begin();
  511.     m_objectPS.Begin();
  512.  
  513.     for(int i=0;i<m_objects.size();i++)
  514.         if(!camera.Cull(m_objects[i].m_BBox))
  515.         {
  516.             D3DXMATRIX m = m_objects[i].m_meshInstance.GetWorldMatrix();
  517.             m_objectVS.SetMatrix(m_objMatW, m);
  518.             m_objects[i].Render();
  519.         }
  520.  
  521.     m_objectVS.End();
  522.     m_objectPS.End();
  523. }
  524.  
  525. void TERRAIN::Progress(std::string text, float prc)
  526. {
  527.     m_pDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  528.     m_pDevice->BeginScene();
  529.     
  530.     RECT rc = {200, 250, 600, 300};
  531.     m_pProgressFont->DrawText(NULL, text.c_str(), -1, &rc, DT_CENTER | DT_VCENTER | DT_NOCLIP, 0xff000000);
  532.         
  533.     //Progress bar
  534.     D3DRECT r;
  535.     r.x1 = 200; r.x2 = 600;
  536.     r.y1 = 300; r.y2 = 340;
  537.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff000000, 1.0f, 0L);
  538.     r.x1 = 202; r.x2 = 598;
  539.     r.y1 = 302; r.y2 = 338;
  540.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  541.     r.x1 = 202; r.x2 = 202 + 396 * prc;
  542.     r.y1 = 302; r.y2 = 338;
  543.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff00ff00, 1.0f, 0L);
  544.  
  545.     m_pDevice->EndScene();
  546.     m_pDevice->Present(0, 0, 0, 0);
  547. }
  548.  
  549. bool TERRAIN::Within(INTPOINT p)
  550. {
  551.     return p.x >= 0 && p.y >= 0 && p.x < m_size.x && p.y < m_size.y;
  552. }
  553.  
  554. void TERRAIN::InitPathfinding()
  555. {
  556.     try
  557.     {
  558.         //Read maptile heights & types from heightmap
  559.         for(int y=0;y<m_size.y;y++)
  560.             for(int x=0;x<m_size.x;x++)
  561.             {
  562.                 MAPTILE *tile = GetTile(x, y);
  563.                 if(m_pHeightMap != NULL)tile->m_height = m_pHeightMap->GetHeight(x, y);
  564.                 tile->m_mappos = INTPOINT(x, y);
  565.                 
  566.                 if(tile->m_height < 0.3f)         tile->m_type = 0;    //Grass
  567.                 else if(tile->m_height < 7.0f) tile->m_type = 1;    //Stone
  568.                 else                         tile->m_type = 2;    //Snow
  569.             }
  570.  
  571.         //Calculate tile cost as a function of the height variance
  572.         for(int y=0;y<m_size.y;y++)        
  573.             for(int x=0;x<m_size.x;x++)
  574.             {
  575.                 MAPTILE *tile = GetTile(x, y);
  576.  
  577.                 if(tile != NULL)
  578.                 {
  579.                     //Possible neighbors
  580.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  581.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  582.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  583.  
  584.                     float variance = 0.0f;
  585.                     int nr = 0;
  586.  
  587.                     //For each neighbor
  588.                     for(int i=0;i<8;i++)    
  589.                         if(Within(p[i]))
  590.                         {
  591.                             MAPTILE *neighbor = GetTile(p[i]);
  592.  
  593.                             if(neighbor != NULL)
  594.                             {
  595.                                 float v = neighbor->m_height - tile->m_height;
  596.                                 variance += (v * v);
  597.                                 nr++;
  598.                             }
  599.                         }
  600.  
  601.                     //Cost = height variance
  602.                     variance /= (float)nr;
  603.                     tile->m_cost = variance + 0.1f;
  604.                     if(tile->m_cost > 1.0f)tile->m_cost = 1.0f;
  605.  
  606.                     //If the tile cost is less than 1.0f, then we can walk on the tile
  607.                     tile->m_walkable = tile->m_cost < 0.5f;
  608.                 }
  609.             }
  610.  
  611.         //Make maptiles with objects on them not walkable
  612.         for(int i=0;i<m_objects.size();i++)
  613.         {
  614.             MAPTILE *tile = GetTile(m_objects[i].m_mappos);
  615.             if(tile != NULL)
  616.             {
  617.                 tile->m_walkable = false;
  618.                 tile->m_cost = 1.0f;
  619.             }
  620.         }
  621.  
  622.         //Connect m_pMapTiles using the neightbors[] pointers
  623.         for(int y=0;y<m_size.y;y++)        
  624.             for(int x=0;x<m_size.x;x++)
  625.             {
  626.                 MAPTILE *tile = GetTile(x, y);
  627.                 if(tile != NULL && tile->m_walkable)
  628.                 {
  629.                     //Clear old connections
  630.                     for(int i=0;i<8;i++)
  631.                         tile->m_pNeighbors[i] = NULL;
  632.  
  633.                     //Possible neighbors
  634.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  635.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  636.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  637.  
  638.                     //For each neighbor
  639.                     for(int i=0;i<8;i++)    
  640.                         if(Within(p[i]))
  641.                         {
  642.                             MAPTILE *neighbor = GetTile(p[i]);
  643.  
  644.                             //Connect tiles if the neighbor is walkable
  645.                             if(neighbor != NULL && neighbor->m_walkable)
  646.                                 tile->m_pNeighbors[i] = neighbor;
  647.                         }
  648.                 }
  649.             }
  650.  
  651.         CreateTileSets();
  652.     }
  653.     catch(...)
  654.     {
  655.         debug.Print("Error in InitPathfinding()");
  656.     }    
  657. }
  658.  
  659. void TERRAIN::CreateTileSets()
  660. {
  661.     try
  662.     {
  663.         int setNo = 0;
  664.         for(int y=0;y<m_size.y;y++)        //Set a unique set for each tile...
  665.             for(int x=0;x<m_size.x;x++)
  666.                 m_pMapTiles[x + y * m_size.x].m_set = setNo++;
  667.  
  668.         bool changed = true;
  669.         while(changed)
  670.         {
  671.             changed = false;
  672.  
  673.             for(int y=0;y<m_size.y;y++)
  674.                 for(int x=0;x<m_size.x;x++)
  675.                 {
  676.                     MAPTILE *tile = GetTile(x, y);
  677.  
  678.                     //Find the lowest m_set of a neighbor
  679.                     if(tile != NULL && tile->m_walkable)
  680.                     {
  681.                         for(int i=0;i<8;i++)
  682.                             if(tile->m_pNeighbors[i] != NULL &&
  683.                                 tile->m_pNeighbors[i]->m_walkable &&
  684.                                 tile->m_pNeighbors[i]->m_set < tile->m_set)
  685.                             {
  686.                                 changed = true;
  687.                                 tile->m_set = tile->m_pNeighbors[i]->m_set;
  688.                             }
  689.                     }
  690.                 }
  691.         }
  692.     }
  693.     catch(...)
  694.     {
  695.         debug.Print("Error in TERRAIN::CreateTileSets()");
  696.     }
  697. }
  698.  
  699. float H(INTPOINT a, INTPOINT b)
  700. {
  701.     //return abs(a.x - b.x) + abs(a.y - b.y);
  702.     return a.Distance(b);
  703. }
  704.  
  705. std::vector<INTPOINT> TERRAIN::GetPath(INTPOINT start, INTPOINT goal)
  706. {
  707.     try
  708.     {
  709.         //Check that the two points are within the bounds of the map
  710.         MAPTILE *startTile = GetTile(start);
  711.         MAPTILE *goalTile = GetTile(goal);
  712.  
  713.         if(!Within(start) || !Within(goal) || start == goal || startTile == NULL || goalTile == NULL)
  714.             return std::vector<INTPOINT>();
  715.  
  716.         //Check if a path exists
  717.         if(!startTile->m_walkable || !goalTile->m_walkable || startTile->m_set != goalTile->m_set)
  718.             return std::vector<INTPOINT>();
  719.  
  720.         //Init Search
  721.         long numTiles = m_size.x * m_size.y;
  722.         for(long l=0;l<numTiles;l++)
  723.         {
  724.             m_pMapTiles[l].f = m_pMapTiles[l].g = INT_MAX;        //Clear F,G
  725.             m_pMapTiles[l].open = m_pMapTiles[l].closed = false;    //Reset Open and Closed
  726.         }
  727.  
  728.         std::vector<MAPTILE*> open;                //Create Our Open list
  729.         startTile->g = 0;                        //Init our starting point (SP)
  730.         startTile->f = H(start, goal);
  731.         startTile->open = true;
  732.         open.push_back(startTile);                //Add SP to the Open list
  733.  
  734.         bool found = false;                    // Search as long as a path hasnt been found,
  735.         while(!found && !open.empty())        // or there is no more tiles to search
  736.         {                                                
  737.             MAPTILE * best = open[0];        // Find the best tile (i.e. the lowest F value)
  738.             int bestPlace = 0;
  739.             for(int i=1;i<open.size();i++)
  740.                 if(open[i]->f < best->f)
  741.                 {
  742.                     best = open[i];
  743.                     bestPlace = i;
  744.                 }
  745.             
  746.             if(best == NULL)break;            //No path found
  747.  
  748.             open[bestPlace]->open = false;
  749.             open.erase(&open[bestPlace]);    // Take the best node out of the Open list
  750.  
  751.             if(best->m_mappos == goal)        //If the goal has been found
  752.             {
  753.                 std::vector<INTPOINT> p, p2;
  754.                 MAPTILE *point = best;
  755.  
  756.                 while(point->m_mappos != start)    // Generate path
  757.                 {
  758.                     p.push_back(point->m_mappos);
  759.                     point = point->m_pParent;
  760.  
  761.                     if(p.size() > 500)        //Too long path, something is wrong
  762.                         return std::vector<INTPOINT>();
  763.                 }
  764.  
  765.                 for(int i=p.size()-1;i!=0;i--)    // Reverse path
  766.                     p2.push_back(p[i]);
  767.                 p2.push_back(goal);
  768.                 return p2;
  769.             }
  770.             else
  771.             {
  772.                 for(i=0;i<8;i++)                    // otherwise, check the neighbors of the
  773.                     if(best->m_pNeighbors[i] != NULL)    // best tile
  774.                     {
  775.                         bool inList = false;        // Generate new G and F value
  776.                         float newG = best->g + 1.0f;
  777.                         float d = H(best->m_mappos, best->m_pNeighbors[i]->m_mappos);
  778.                         float newF = newG + H(best->m_pNeighbors[i]->m_mappos, goal) + best->m_pNeighbors[i]->m_cost * 5.0f * d;
  779.  
  780.                         if(best->m_pNeighbors[i]->open || best->m_pNeighbors[i]->closed)
  781.                         {
  782.                             if(newF < best->m_pNeighbors[i]->f)    // If the new F value is lower
  783.                             {
  784.                                 best->m_pNeighbors[i]->g = newG;    // update the values of this tile
  785.                                 best->m_pNeighbors[i]->f = newF;
  786.                                 best->m_pNeighbors[i]->m_pParent = best;                                
  787.                             }
  788.                             inList = true;
  789.                         }
  790.  
  791.                         if(!inList)            // If the neighbor tile isn't in the Open or Closed list
  792.                         {
  793.                             best->m_pNeighbors[i]->f = newF;        //Set the values
  794.                             best->m_pNeighbors[i]->g = newG;
  795.                             best->m_pNeighbors[i]->m_pParent = best;
  796.                             best->m_pNeighbors[i]->open = true;
  797.                             open.push_back(best->m_pNeighbors[i]);    //Add it to the open list    
  798.                         }
  799.                     }
  800.  
  801.                 best->closed = true;        //The best tile has now been searched, add it to the Closed list
  802.             }
  803.         }
  804.  
  805.         return std::vector<INTPOINT>();        //No path found, return an empty path
  806.         
  807.     }
  808.     catch(...)
  809.     {
  810.         debug.Print("Error in TERRAIN::GetPath()");
  811.         return std::vector<INTPOINT>();
  812.     }
  813. }
  814.  
  815. MAPTILE* TERRAIN::GetTile(int x, int y)
  816. {
  817.     if(m_pMapTiles == NULL)return NULL;
  818.  
  819.     try
  820.     {
  821.         return &m_pMapTiles[x + y * m_size.x];
  822.     }
  823.     catch(...)
  824.     {
  825.         return NULL;
  826.     }
  827. }
  828.  
  829. void TERRAIN::SaveTerrain(char fileName[])
  830. {
  831.     try
  832.     {
  833.         std::ofstream out(fileName, std::ios::binary);        //Binary format
  834.  
  835.         if(out.good())
  836.         {
  837.             out.write((char*)&m_size, sizeof(INTPOINT));    //Write map size
  838.  
  839.             //Write all the maptile information needed to recreate the map
  840.             for(int y=0;y<m_size.y;y++)
  841.                 for(int x=0;x<m_size.x;x++)
  842.                 {
  843.                     MAPTILE *tile = GetTile(x, y);
  844.                     out.write((char*)&tile->m_type, sizeof(int));            //type
  845.                     out.write((char*)&tile->m_height, sizeof(float));        //Height
  846.                 }
  847.  
  848.             //Write all the objects
  849.             int numObjects = m_objects.size();
  850.             out.write((char*)&numObjects, sizeof(int));     //Num Objects
  851.             for(int i=0;i<m_objects.size();i++)
  852.             {
  853.                 out.write((char*)&m_objects[i].m_type, sizeof(int));                        //type
  854.                 out.write((char*)&m_objects[i].m_mappos, sizeof(INTPOINT));                    //mappos
  855.                 out.write((char*)&m_objects[i].m_meshInstance.m_pos, sizeof(D3DXVECTOR3));    //Pos
  856.                 out.write((char*)&m_objects[i].m_meshInstance.m_rot, sizeof(D3DXVECTOR3));    //Rot
  857.                 out.write((char*)&m_objects[i].m_meshInstance.m_sca, sizeof(D3DXVECTOR3));    //Sca
  858.             }
  859.         }
  860.  
  861.         out.close();
  862.     }
  863.     catch(...)
  864.     {
  865.         debug.Print("Error in TERRAIN::SaveTerrain()");
  866.     }
  867. }
  868.  
  869. void TERRAIN::LoadTerrain(char fileName[])
  870. {
  871.     try
  872.     {
  873.         std::ifstream in(fileName, std::ios::binary);        //Binary format
  874.  
  875.         if(in.good())
  876.         {
  877.             Release();    //Release all terrain resources
  878.  
  879.             in.read((char*)&m_size, sizeof(INTPOINT));    //read map size
  880.         
  881.             if(m_pMapTiles != NULL)    //Clear old m_pMapTiles
  882.                 delete [] m_pMapTiles;
  883.  
  884.             //Create new m_pMapTiles
  885.             m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  886.             memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  887.  
  888.  
  889.             //Read the maptile information
  890.             for(int y=0;y<m_size.y;y++)
  891.                 for(int x=0;x<m_size.x;x++)
  892.                 {
  893.                     MAPTILE *tile = GetTile(x, y);
  894.                     in.read((char*)&tile->m_type, sizeof(int));            //type
  895.                     in.read((char*)&tile->m_height, sizeof(float));        //Height
  896.                 }
  897.  
  898.             //Read number of objects
  899.             int numObjects = 0;
  900.             in.read((char*)&numObjects, sizeof(int));
  901.             for(int i=0;i<numObjects;i++)
  902.             {
  903.                 int type = 0;
  904.                 INTPOINT mp;
  905.                 D3DXVECTOR3 p, r, s;
  906.  
  907.                 in.read((char*)&type, sizeof(int));            //type
  908.                 in.read((char*)&mp, sizeof(INTPOINT));        //mappos
  909.                 in.read((char*)&p, sizeof(D3DXVECTOR3));    //Pos
  910.                 in.read((char*)&r, sizeof(D3DXVECTOR3));    //Rot
  911.                 in.read((char*)&s, sizeof(D3DXVECTOR3));    //Sca
  912.  
  913.                 m_objects.push_back(OBJECT(type, mp, p, r, s));
  914.             }
  915.  
  916.             //Recreate Terrain
  917.             InitPathfinding();
  918.             CreatePatches(3);
  919.             CalculateAlphaMaps();
  920.             CalculateLightMap(true);
  921.         }
  922.  
  923.         in.close();
  924.     }
  925.     catch(...)
  926.     {
  927.         debug.Print("Error in TERRAIN::LoadTerrain()");
  928.     }
  929. }
  930.  
  931. D3DXVECTOR3 TERRAIN::GetWorldPos(INTPOINT mappos)
  932. {
  933.     if(!Within(mappos))return D3DXVECTOR3(0, 0, 0);
  934.     MAPTILE *tile = GetTile(mappos);
  935.     return D3DXVECTOR3(mappos.x, tile->m_height, -mappos.y);
  936. }